package com.gdut.simple.event;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import rx.Observable;
import rx.Subscriber;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

public class RxBus {

    private static volatile RxBus mDefaultInstance;

    private final Subject<Object, Object> mBus;

    private final Map<Class<?>, Object> mStickyEventMap;

    private RxBus() {
        mBus = new SerializedSubject<>(PublishSubject.create());
        mStickyEventMap = new ConcurrentHashMap<>();
    }

    public static RxBus getDefault() {
        if (mDefaultInstance == null) {
            synchronized (RxBus.class) {
                if (mDefaultInstance == null) {
                    mDefaultInstance = new RxBus();
                }
            }
        }
        return mDefaultInstance;
    }

    /**
     * 发送事件
     */
    public void post(Object o) {
        mBus.onNext(o);
    }

    /**
     * 根据传递的eventType类型返回特定的被观察者
     */
    public <T> Observable<T> toObservable(Class<T> eventType) {
        return mBus.ofType(eventType);
    }

    /**
     * 判断是否有订阅者
     */
    public boolean hasObservers() {
        return mBus.hasObservers();
    }

    public void reset() {
        mDefaultInstance = null;
    }

    public void postSticky(Object event) {
        mStickyEventMap.put(event.getClass(), event);
        post(event);
    }

    public <T> Observable<T> toObservableSticky(final Class<T> eventType) {
        Observable<T> observable = mBus.ofType(eventType);
        final Object event = mStickyEventMap.get(eventType);

        if (event != null) {
            return observable.mergeWith(Observable.create(new Observable.OnSubscribe<T>() {
                @Override
                public void call(Subscriber<? super T> subscriber) {
                    subscriber.onNext(eventType.cast(event));
                }
            }));
        } else {
            return observable;
        }
    }

    public <T> T getStickyEvent(Class<T> eventType) {
        return eventType.cast(mStickyEventMap.get(eventType));
    }

    public <T> T removeStickyEvent(Class<T> eventType) {
        return eventType.cast(mStickyEventMap.remove(eventType));
    }

    public void removeAllStickyEvents() {
        mStickyEventMap.clear();
    }

}
